package afeng.world.pangu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;

/**
 * @datetime: 2020/9/6 18:03
 * @project_name: pangu
 * @author: afeng
 */
//@Service
public class MailServiceImpl implements MailService {

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    String from;
    @Value("${spring.mail.to-username}")
    String to;

    // TODO: 2020/9/6 @Async多线程是怎么样创建的, 有限制吗? 高并发下会宕机吗?
    @Async
    @Override
    public void sendTest() {

//        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//        simpleMailMessage.setTo(XXX);
//        javaMailSender.send(simpleMailMessage);
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true 表⽰示需要创建⼀一个 multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to); //发送给to
            helper.setSubject("月神运动");
            Date date = new Date();
            String hostAddress = InetAddress.getLocalHost().getHostAddress();

            String text = "[启动时间:"+date.toString()+"]\n" +
                    "[主机内网:"+hostAddress+"]\n" ;
            helper.setText(text, true);
            javaMailSender.send(message);

        } catch (MessagingException | IOException e) {
            e.printStackTrace();

        }
    }
}
